<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function $(id){
            return document.getElementById(id);
        }

        var speakArray = [];
        function addSpeak(){
            //将文本框内容封装成评论对象
            // var speakObj = new Object();
            // speakObj.name = $("speakTxt").value;
            // speakObj.content = $("contentTxt").value;

            if(checkForm('speakTxt',/^[a-zA-Z\u4e00-\u9fa5]{2,}$/,'nameSpan','评论人必须是2位以上字母或汉字') == false
                | checkForm('contentTxt',/^\w{3,}$/,'contentSpan','至少写3个字') == false){
                return;
            }

            var name = $("speakTxt").value;
            //速写属性，当属性名和属性值变量同名时，可以省去属性值
            var speakObj = {name, content:$("contentTxt").value};
            //将评论对象加入数组
            speakArray.push(speakObj);

            //将数组内容展示在表格中
            showTable();
        }

        function showTable(){
            var str = "";
            speakArray.forEach(n =>{
                str += `<tr><td>${n.name}</td><td>${n.content}</td></tr>`;
            });
            $("data").innerHTML = str;
            //清空文本框的内容
            $("speakTxt").value = "";
            $("contentTxt").value = "";
        }

        function checkForm(txtId,rex,spanId,errorInfo){
            if(rex.test($(txtId).value)){
                $(spanId).style.color = "green";
                $(spanId).innerHTML = "验证通过";
                return true;
            }
            else{
                $(spanId).style.color = "red";
                $(spanId).innerHTML = errorInfo;
                return false;
            }
        }
    </script>
</head>
<body>
    <div style="display:flex">
        <img src="../../img/6.jpg" width="200" height="200">
        <div>
            商品名：女士衬衫<br>
            单价：￥35元<br>
            介绍：这是女士羊毛衫
        </div>
    </div>
    <table border="1" cellspacing="0" width="60%">
        <thead>
            <tr><th>评论人</th><th>评论内容</th></tr>
        </thead>
        <tbody id="data"></tbody>
    </table>
    评论人：<input type="text" id="speakTxt" onblur="checkForm('speakTxt',/^[a-zA-Z\u4e00-\u9fa5]{2,}$/,'nameSpan','评论人必须是2位以上字母或汉字')"><br>
        <span id="nameSpan"></span>
    <br>
    评论内容：<input type="text" id="contentTxt" onblur="checkForm('contentTxt',/^\w{3,}$/,'contentSpan','至少写3个字')"><br>
    <span id="contentSpan"></span><br>
    <input type="button" value="评论" onclick="addSpeak()"><br>
</body>
</html>